package com.example.shopbusiness.service.impl;

import com.example.shopcommon.feign.OrderFeignClient;
import com.example.shopcommon.feign.ProductFeignClient;
import com.example.shopbusiness.service.BusinessService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @GlobalTransactional(rollbackFor = Exception.class)
    public void purchase(Long userId, Long pid, int orderCount, boolean rollback) {
        String result = productFeignClient.deduct(pid, orderCount);

        if (!"SUCCESS".equals(result)) {
            throw new RuntimeException("库存服务调用失败,事务回滚!");
        }

        result = orderFeignClient.create(userId, pid, orderCount);

        if (!"SUCCESS".equals(result)) {
            throw new RuntimeException("订单服务调用失败,事务回滚!");
        }

        if (rollback) {
            throw new RuntimeException("Force rollback ... ");
        }
    }
}
